<template>
  <div class="divination-stats">
    <el-card class="filter-card">
      <el-form :model="filterForm" label-width="80px" inline>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="占卜类型">
          <el-select v-model="filterForm.divinationType" placeholder="请选择占卜类型" clearable>
            <el-option label="梅花易数" value="plum-blossom" />
            <el-option label="六爻" value="six-yao" />
            <el-option label="奇门遁甲" value="qi-men" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">筛选</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 统计概览 -->
    <el-row :gutter="20" class="stats-overview">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #409eff">
              <i class="el-icon-magic-stick"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsOverview.totalDivinations }}</div>
              <div class="stat-label">总占卜次数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #67c23a">
              <i class="el-icon-star-on"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsOverview.aiInterpretations }}</div>
              <div class="stat-label">AI解释次数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #e6a23c">
              <i class="el-icon-chat-line-square"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsOverview.userFeedback }}</div>
              <div class="stat-label">用户反馈</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #f56c6c">
              <i class="el-icon-sunset"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsOverview.accuracyRate }}%</div>
              <div class="stat-label">准确率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 图表区域 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>占卜类型分布</span>
            </div>
          </template>
          <div ref="divinationTypeChart" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>占卜时间分布</span>
            </div>
          </template>
          <div ref="divinationTimeChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 占卜记录列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>占卜记录</span>
        </div>
      </template>
      
      <el-table :data="divinationList" stripe style="width: 100%">
        <el-table-column prop="id" label="记录ID" width="80" />
        <el-table-column prop="username" label="用户" />
        <el-table-column prop="type" label="占卜类型" width="120">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.type)">
              {{ getTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="question" label="问题" />
        <el-table-column prop="result" label="结果" width="150" />
        <el-table-column prop="useAi" label="AI解释" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.useAi ? 'success' : 'info'">
              {{ scope.row.useAi ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="占卜时间" width="180" />
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, computed } from 'vue'
import * as echarts from 'echarts'
import { useStatsStore } from '@/stores'

// 使用统计store
const statsStore = useStatsStore()

// 筛选表单
const filterForm = reactive({
  dateRange: [],
  divinationType: ''
})

// 统计概览（从store中获取）
const statsOverview = computed(() => statsStore.divinationStats)

// 图表实例
const divinationTypeChart = ref(null)
const divinationTimeChart = ref(null)
let divinationTypeChartInstance = null
let divinationTimeChartInstance = null

// 加载状态
const loading = computed(() => statsStore.loading)

// 获取类型标签类型
const getTypeTagType = (type) => {
  switch (type) {
    case 'plum-blossom':
      return 'primary'
    case 'six-yao':
      return 'success'
    case 'qi-men':
      return 'warning'
    default:
      return 'info'
  }
}

// 获取类型文本
const getTypeText = (type) => {
  switch (type) {
    case 'plum-blossom':
      return '梅花易数'
    case 'six-yao':
      return '六爻'
    case 'qi-men':
      return '奇门遁甲'
    default:
      return '未知'
  }
}

// 处理筛选
const handleFilter = async () => {
  const params = {
    dateRange: filterForm.dateRange,
    divinationType: filterForm.divinationType
  }
  
  try {
    // 获取占卜统计数据
    await statsStore.fetchDivinationStats(params)
    
    // 获取图表数据
    await statsStore.fetchDivinationTypeDistribution(params)
    await statsStore.fetchDivinationTimeDistribution(params)
    
    // 更新图表
    updateDivinationTypeChart()
    updateDivinationTimeChart()
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 处理重置
const handleReset = () => {
  filterForm.dateRange = []
  filterForm.divinationType = ''
  handleFilter()
}

// 初始化占卜类型分布图表
const initDivinationTypeChart = () => {
  if (!divinationTypeChart.value) return
  
  divinationTypeChartInstance = echarts.init(divinationTypeChart.value)
  
  const option = {
    title: {
      text: '占卜类型分布'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: 'bottom'
    },
    series: [
      {
        name: '占卜类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: []
      }
    ]
  }
  
  divinationTypeChartInstance.setOption(option)
}

// 更新占卜类型分布图表
const updateDivinationTypeChart = () => {
  if (!divinationTypeChartInstance || !statsStore.divinationTypeDistribution.length) return
  
  const chartData = statsStore.divinationTypeDistribution.map(item => ({
    value: item.count,
    name: getTypeText(item.type)
  }))
  
  divinationTypeChartInstance.setOption({
    series: [
      {
        data: chartData
      }
    ]
  })
}

// 初始化占卜时间分布图表
const initDivinationTimeChart = () => {
  if (!divinationTimeChart.value) return
  
  divinationTimeChartInstance = echarts.init(divinationTimeChart.value)
  
  const option = {
    title: {
      text: '占卜时间分布'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [],
        type: 'bar',
        itemStyle: {
          color: '#409eff'
        }
      }
    ]
  }
  
  divinationTimeChartInstance.setOption(option)
}

// 更新占卜时间分布图表
const updateDivinationTimeChart = () => {
  if (!divinationTimeChartInstance || !statsStore.divinationTimeDistribution.length) return
  
  const xAxisData = statsStore.divinationTimeDistribution.map(item => item.timeRange)
  const seriesData = statsStore.divinationTimeDistribution.map(item => item.count)
  
  divinationTimeChartInstance.setOption({
    xAxis: {
      data: xAxisData
    },
    series: [
      {
        data: seriesData
      }
    ]
  })
}

// 获取统计数据
const fetchStatsData = async () => {
  try {
    // 获取占卜统计数据
    await statsStore.fetchDivinationStats()
    
    // 获取图表数据
    await statsStore.fetchDivinationTypeDistribution()
    await statsStore.fetchDivinationTimeDistribution()
    
    // 更新图表
    updateDivinationTypeChart()
    updateDivinationTimeChart()
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 组件挂载后初始化图表和获取数据
onMounted(() => {
  initDivinationTypeChart()
  initDivinationTimeChart()
  fetchStatsData()
  
  // 监听窗口大小变化，重新调整图表大小
  window.addEventListener('resize', () => {
    if (divinationTypeChartInstance) {
      divinationTypeChartInstance.resize()
    }
    if (divinationTimeChartInstance) {
      divinationTimeChartInstance.resize()
    }
  })
})

// 组件卸载前销毁图表实例
onBeforeUnmount(() => {
  if (divinationTypeChartInstance) {
    divinationTypeChartInstance.dispose()
  }
  if (divinationTimeChartInstance) {
    divinationTimeChartInstance.dispose()
  }
})
</script>

<style lang="scss" scoped>
.divination-stats {
  .filter-card {
    margin-bottom: 20px;
  }
  
  .stats-overview {
    margin-bottom: 20px;
    
    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;
        
        .stat-icon {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 20px;
          
          i {
            font-size: 30px;
            color: white;
          }
        }
        
        .stat-info {
          .stat-value {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 5px;
          }
          
          .stat-label {
            color: #999;
          }
        }
      }
    }
  }
  
  .chart-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .chart-container {
      height: 400px;
    }
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>